//本文件存储级联选择器用户选择的数据
import { defineStore } from 'pinia';

export const useDataStore = defineStore('data', {
  state: () => ({
    selectedOptions: [], // 存储父组件选择的数据
    selectedData: [],
    isLoading: false,    // 共享加载状态
  }),
  actions: {
    // 父组件调用：更新选项数据
    setSelectedOptions(options) {
      this.selectedOptions = options;
      console.log("新数据selectedOptions",this.selectedOptions);
      this.isLoading = true;
    },
    // 子组件调用：更新数据
    setSelectedData(data) {
      this.selectedData = data;
    },
    // 子组件调用：获取数据（模拟异步操作）
    async fetchData(dataScore, zhibiao) {
      try {
        this.isLoading = true;
        this.error = null;
        this.currentZhibiao = zhibiao;

        const requests = dataScore.selectedData.map(item =>
          axios({
            url: '/xiangxi',
            method: 'GET',
            headers: {
              Authorization: "Bearer " + localStorage.getItem("jwt_token")
            },
            params: {
              zhibiao: zhibiao,
              code: item.xxdm,
              xnzymc: item.xnzymc
            }
          }).catch(error => {
            console.error("请求失败:", error);
            return null;
          })
        );

        const responses = await Promise.all(requests);
        const validData = responses.filter(res => res !== null);

        let processedData = validData.map(res => {
          let dataItems = res?.data?.[0]?.data || {};
          if (dataItems.length === 0) {
            return undefined;
          }
          return dataItems.flatMap(item => ({
            xxmc: item.xxmc || item.xwdm || "无该校数据",
            major: item.xnzymc || item.major || '无数据',
            index: "高层次称号",
            jsxm: item.jsxm || '无数据',
            rclx: item.rclx || '无数据',
            fd: item.df ?? '无数据',
          }));
        });

        // 处理单对象数组
        processedData = this.extractSingleObjects(processedData);
        processedData = processedData.filter(item => item !== undefined);
        processedData = processedData.flatMap(item =>
          Array.isArray(item) ? item : [item]
        );

        this.tableData = processedData;
      } catch (error) {
        this.error = error.message || '获取数据失败';
        console.error('Error fetching data:', error);
      } finally {
        this.isLoading = false;
      }
    },
    extractSingleObjects(arr) {
      return arr.map(item => {
        if (Array.isArray(item) && item.length === 1 && typeof item[0] === 'object' && item[0] !== null) {
          return item[0];
        }
        return item;
      });
    }
  },
});
